import React, { useState } from 'react';
import { Form, Input, Button, Toast, NavBar, ImageUploader } from 'antd-mobile';
import { useNavigate, Link } from 'react-router-dom';
import { PictureOutline } from 'antd-mobile-icons';
import { register, uploadAvatar } from '../../../services/auth';
import styles from './index.module.css';

interface ImageItem {
  url: string;
}

const RegisterPage: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [avatar, setAvatar] = useState<ImageItem[]>([]);

  // 上传头像
  const handleAvatarUpload = async (file: File): Promise<ImageItem> => {
    try {
      // 调用API上传头像
      const avatarUrl = await uploadAvatar(file);
      Toast.show({
        icon: 'success',
        content: '头像上传成功',
      });
      return { url: avatarUrl };
    } catch (error) {
      Toast.show({
        icon: 'fail',
        content: '头像上传失败，请重试',
      });
      throw error;
    }
  };

  // 提交注册
  const onFinish = async (values: { username: string; password: string; nickname: string }) => {
    try {
      setLoading(true);

      // 准备注册数据
      const registerData = {
        ...values,
        avatar: avatar.length > 0 ? avatar[0].url : undefined, // 如果没有上传头像，使用默认头像
      };

      await register(registerData);

      Toast.show({
        icon: 'success',
        content: '注册成功',
      });

      // 注册成功后跳转到首页
      navigate('/');
    } catch (error: any) {
      const errorMsg = error.response?.data?.message || '注册失败，请重试';
      Toast.show({
        icon: 'fail',
        content: errorMsg,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.registerPage}>
      <NavBar onBack={() => navigate(-1)}>用户注册</NavBar>

      <div className={styles.formContainer}>
        <h2 className={styles.title}>创建账号</h2>
        <p className={styles.subtitle}>加入旅游日记，记录精彩旅程</p>
        
        {/* 头像上传放在最上方并居中 */}
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          marginBottom: '2vh', /* 减小下边距 */
          width: '100%'
        }}>
          <Form.Item name='avatar' label='' style={{ marginBottom: 0 }}>
            <ImageUploader
              value={avatar}
              onChange={setAvatar}
              upload={handleAvatarUpload}
              maxCount={1}
              showUpload={avatar.length < 1}
            >
              <div className={styles.uploaderButton}>
                <PictureOutline fontSize={16} /> {/* 固定图标大小 */}
                <span>上传头像</span>
              </div>
            </ImageUploader>
          </Form.Item>
        </div>

        <Form
          form={form}
          layout='vertical'
          onFinish={onFinish}
          style={{ width: '100%' }}
          footer={
            <Button 
              block 
              type='submit' 
              color='primary' 
              loading={loading}
              style={{
                marginTop: '2vh', /* 减小上边距 */
                height: 'clamp(36px, 5vh, 44px)', /* 减小按钮高度 */
                borderRadius: '8px',
                fontSize: 'clamp(14px, 2.5vw, 16px)' /* 减小字体大小 */
              }}
            >
              注册
            </Button>
          }
        >
          {/* 减小表单项间距 */}
          <Form.Item
            name='nickname'
            label='昵称'
            rules={[{ required: true, message: '请输入昵称' }]}
            style={{ marginBottom: '1.5vh' }} /* 减小下边距 */
          >
            <Input placeholder='请输入昵称' />
          </Form.Item>

          <Form.Item
            name='username'
            label='用户名'
            rules={[{ required: true, message: '请输入用户名' }]}
            style={{ marginBottom: '1.5vh' }} /* 减小下边距 */
          >
            <Input placeholder='请输入用户名' />
          </Form.Item>

          <Form.Item
            name='password'
            label='密码'
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6位' }
            ]}
            style={{ marginBottom: '1vh' }} /* 减小下边距 */
          >
            <Input placeholder='请输入密码' type='password' />
          </Form.Item>
        </Form>

        <div className={styles.loginLink}>
          <span>已有账号？</span>
          <Link to="/auth/login">立即登录</Link>
        </div>
      </div>
    </div>
  );
};

export default RegisterPage;